import { Sprite } from "cc"
import { _decorator, Component, Node } from "cc"
import { UITransform } from "cc"
const { ccclass, property } = _decorator

@ccclass("GameItemHp")
export class GameItemHp extends Component {
  @property(Node)
  nodePlayerHp: Node = null!

  @property(Node)
  nodeEnemyHp: Node = null!

  @property(Node)
  nodeShield: Node = null!

  private hpSprite: Sprite = null

  private followTarget: Node = null

  private isEnemy: boolean = false

  private sprShield:Sprite = null

  init(target: Node, isEnemy: boolean) {
    if (!target || !target.isValid) {
      this.node.destroy()
    }

    this.followTarget = target
    this.isEnemy = isEnemy
    this.nodePlayerHp.active = !isEnemy
    this.nodeEnemyHp.active = isEnemy
    this.nodeShield.active = !isEnemy
    this.sprShield = this.nodeShield.getComponent(Sprite)
    this.updateItemShieldHp(0,1)
    if (isEnemy) {
      this.hpSprite = this.nodeEnemyHp.getComponent(Sprite)
    } else {
      this.hpSprite = this.nodePlayerHp.getComponent(Sprite)
    }
    this.node.positionX = target.positionX
    this.node.positionY = target.positionY - 83
  }

  protected onLoad(): void {
    this.totalWidth = this.nodePlayerHp.getComponent(UITransform).width
  }

  start() {}

  update(deltaTime: number) {
    const target = this.followTarget
    if (!target || !target.isValid) {
      return
    }

    this.node.positionX = target.positionX
    this.node.positionY = target.positionY - 83
  }

  private totalWidth: number = 0
  public updateItemHp(currHp: number, maxHp: number) {
    this.hpSprite.fillRange = currHp / maxHp
  }

  public updateItemShieldHp(curShieldHp: number, maxShieldHp: number){
    // this.node
    this.sprShield.fillRange = curShieldHp / maxShieldHp
  } 
}
